import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pagewise/flutter_pagewise.dart';
import 'package:loxen/api/http_server/dictionaries.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/inspiration/inspiration_info_bean.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/format_time.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/login_view_model.dart';
import 'package:loxen/viewmode/search_result_viewmodel.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class SearchInspirationList extends StatelessWidget {
  final PagewiseLoadController pageLoadController;

  SearchInspirationList({Key key, this.pageLoadController}) : super(key: key) {
    pageLoadController.init();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(left: 36.w, top: 31.h),
      child: RefreshIndicator(
        onRefresh: () async {
          Provider.of<SearchResultViewModel>(context, listen: false).refresh();
          this.pageLoadController.reset();
        },
        child: PagewiseListView<InspirationInfo>(
          addAutomaticKeepAlives: false,
          loadingBuilder: (_) => MySubassembly.getLoadingItem(),
          noItemsFoundBuilder: (_) => MySubassembly.getNullItem(msg: '没有更多内容'),
          itemBuilder: (_, entity, index) {
            return _ItemWidget(
              entity: entity,
            );
          },
          pageLoadController: this.pageLoadController,
        ),
      ),
    );
  }
}

class _ItemWidget extends StatelessWidget {
  final InspirationInfo entity;
  static const Widget empty = const SizedBox.shrink();

  const _ItemWidget({Key key, this.entity}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          height: 450.h,
          child: GestureDetector(
            onTap: () {
              Navigator.of(context)
                  .pushNamed(Routes.inspiration_detail, arguments: entity)
                  .then((value) {
                context.read<SearchResultViewModel>().changeEntity();
              });
            },
            child: Stack(
              children: <Widget>[
                Container(
                  child: entity.images != null
                      ? ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: entity.images.length,
                          itemBuilder: (context, index) {
                            return CachedNetworkImage(
                              imageUrl: ImageUrlUtil.getClean(entity.images[index]),
                              fit: BoxFit.cover,
                            );
                          },
                        )
                      : Image.network(
                          entity.cover,
                          width: MediaQuery.of(context).size.width,
                          fit: BoxFit.cover,
                        ),
                ),
                entity.tag != ''
                    ? Positioned(
                        top: 28.h,
                        child: Stack(
                          children: <Widget>[
                            Image.asset(
                              'images/orangeBg.png',
                              width: 50,
                              height: 20,
                              fit: BoxFit.cover,
                            ),
                            Padding(
                                padding: EdgeInsets.only(left: 23.w, top: 2.h),
                                child: Text(
                                  entity.tag,
                                  style: TextStyle(
                                      fontSize: 20.sp,
                                      fontWeight: FontWeight.w500,
                                      color: Colors.white),
                                ))
                          ],
                        ))
                    : empty,
              ],
            ),
          ),
        ),
        Padding(
          padding: EdgeInsets.only(top: 15.h),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Expanded(
                  child: Text(
                entity.title,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 27.sp,
                  fontWeight: FontWeight.w500,
                ),
              )),
              Padding(
                  padding: EdgeInsets.only(right: 36.w),
                  child: Text(
                    FormatTime.readTimestamp(entity.add_time),
                    style: TextStyle(
                        color: Color(0xFF999999), fontSize: 20.sp, fontWeight: FontWeight.w500),
                  ))
            ],
          ),
        ),
        Container(
          margin: EdgeInsets.only(bottom: 30.h),
          child: Row(
            children: <Widget>[
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    Navigator.of(context)
                        .pushNamed(Routes.mine_user_info, arguments: entity.user.userId.toString());
                  },
                  child: Row(
                    children: <Widget>[
                      Container(
                          width: 52.w,
                          height: 52.w,
                          decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              image: DecorationImage(
                                  image: NetworkImage(
                                    entity?.user?.portrait,
                                  ),
                                  fit: BoxFit.cover))),
                      Padding(
                        padding: EdgeInsets.only(left: 15.w),
                        child: Text(
                          entity?.user?.nickname,
                          style: TextStyle(color: Color(0xFF999999), fontSize: 21.sp),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              Selector<SearchResultViewModel, int>(
                builder: (_, __, ___) {
                  return Padding(
                    padding: EdgeInsets.only(right: 20.w),
                    child: SizedBox(
                      width: 72.w,
                      child: FlatButton(
                        padding: EdgeInsets.all(1.w),
                        onPressed: () {
                          if (context.read<LoginViewModel>().isLogin()) {
                            Navigator.of(context).pushNamed(Routes.login_page).then((value) {
                              if (context.read<LoginViewModel>().isLogin()) {
                                Provider.of<SearchResultViewModel>(context, listen: false)
                                    .loadData();
                              }
                            });
                          } else {
                            context.read<SearchResultViewModel>().like(entity);
                          }
                        },
                        child: Stack(
                          alignment: Alignment.centerLeft,
                          children: <Widget>[
                            Image.asset(
                              entity.is_like == 0 ? "images/like.png" : "images/like_active.png",
                              width: 30.w,
                              height: 30.w,
                              fit: BoxFit.cover,
                            ),
                            Padding(
                              padding: EdgeInsets.only(
                                left: 37.w,
                                top: 4.h,
                              ),
                              child: Text(
                                '${entity.like_num}',
                                style: TextStyle(
                                    fontSize: 22.sp,
                                    color: entity.is_like == 0
                                        ? Color(0xFF999999)
                                        : Color(0xFF999999)),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  );
                },
                selector: (_, __) => entity.is_like,
                shouldRebuild: (old, next) => old != next,
              ),
              Padding(
                padding: EdgeInsets.only(right: 20.w),
                child: SizedBox(
                  width: 72.w,
                  child: FlatButton(
                    padding: EdgeInsets.all(1.w),
                    onPressed: () {
                      Navigator.of(context)
                          .pushNamed(Routes.inspiration_detail, arguments: entity)
                          .then((value) {
                        context.read<SearchResultViewModel>().changeEntity();
                      });
                    },
                    child: Stack(
                      alignment: Alignment.centerLeft,
                      children: <Widget>[
                        Image.asset(
                          'images/comment.png',
                          width: 30.w,
                          height: 30.w,
                          fit: BoxFit.cover,
                        ),
                        Padding(
                          padding: EdgeInsets.only(
                            left: 37.w,
                            top: 4.h,
                          ),
                          child: Text(
                            '${entity.comment_num}',
                            style: TextStyle(fontSize: 22.sp, color: Color(0xFF999999)),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              Builder(builder: (context) {
                bool collection =
                    context.select<SearchResultViewModel, bool>((value) => entity.is_collect == 0);
                return Padding(
                  padding: EdgeInsets.only(right: 30.w),
                  child: SizedBox(
                    width: 72.w,
                    child: FlatButton(
                      padding: EdgeInsets.all(1.w),
                      onPressed: () async {
                        if (context.read<LoginViewModel>().isLogin()) {
                          Navigator.of(context).pushNamed(Routes.login_page);
                          return;
                        }
                        if (collection) {
                          Navigator.of(context).pushNamed(Routes.master_file_add, arguments: {
                            'type': FileType.INSPIRATION,
                            'id': entity.id.toString()
                          }).then((value) {
                            if (value) {
                              entity.is_collect = 1;
                              entity.collect_num += 1;
                              context.read<SearchResultViewModel>().changeEntity();
                            }
                          });
                        } else {
                          bool data = await showDialog(
                              context: context,
                              builder: (context) => AlertDialog(
                                    title: Text('提示'),
                                    content: Text(
                                      '是否取消收藏？',
                                      style: TextStyle(color: Colors.black),
                                    ),
                                    actions: <Widget>[
                                      FlatButton(
                                        child: Text(StringResources.qu_xiao),
                                        onPressed: () => Navigator.of(context).pop(),
                                      ),
                                      FlatButton(
                                        child: Text(StringResources.que_ding),
                                        onPressed: () {
                                          Navigator.of(context).pop(true);
                                        },
                                      ),
                                    ],
                                  ));
                          if (data != null && data) {
                            context.read<SearchResultViewModel>().unCollection(entity.id.toString(),
                                onSuccess: () {
                              entity.is_collect = 0;
                              entity.collect_num -= 1;
                              Toast.show(StringResources.qu_xiao_shou_cang, context);
                            }, onError: (str) {
                              Toast.show(StringResources.wang_luo_yi_chang, context);
                            });
                          }
                        }
                      },
                      child: Stack(
                        alignment: Alignment.centerLeft,
                        children: <Widget>[
                          Image.asset(
                            collection ? "images/collect.png" : "images/collected.png",
                            width: 30.w,
                            height: 30.w,
                            fit: BoxFit.cover,
                          ),
                          Padding(
                            padding: EdgeInsets.only(
                              left: 37.w,
                              top: 4.h,
                            ),
                            child: Text(
                              '${entity.collect_num}',
                              style: TextStyle(
                                  fontSize: 22.sp,
                                  color: collection ? Color(0xFF999999) : Color(0xFF0CABCB)),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                );
              }),
            ],
          ),
        )
      ],
    );
  }
}
